import PropTypes from 'prop-types'
import './Progress.css'

// 反转排序
let reverseArr = (arr: any[]) => {
  let newArr = []
  for (let i = arr.length - 1; i >= 0; i--) {
    newArr.push(arr[i])
  }
  return newArr
}

//随机生成十六进制颜色
function randomHexColor(random: number) {
  var hex = Math.floor(Math.random() * 16777216 - random).toString(16) //生成ffffff以内16进制数
  while (hex.length < 6) {
    //while循环判断hex位数，少于6位前面加0凑够6位
    hex = '0' + hex
  }
  return '#' + hex //返回‘#'开头16进制颜色
}

/**
 * 进度条组件
 * @param {themeColor} string 进度条的颜色
 * @param {percent} number 进度值百分比
 * @param {autoHidden} boolean 是否进度到100%时自动消失
 * @param {hiddenText} boolean 是否隐藏进度条文本
 * @param {width} string|number 进度条的宽度
 * @param {textColor} string 进度文本颜色
 * @param {statusScope} array 状态阈值,传入进度条的阶段及阶段名称,为一个数组
 */
function Progress(props: {
  themeColor?: string | undefined
  percent?: number | undefined
  autoHidden?: boolean | undefined
  hiddenText?: boolean | undefined
  width?: number | undefined
  textColor?: string | undefined
  statusScope: any
}) {
  let {
    themeColor = '#06f',
    percent = 0,
    autoHidden = false,
    hiddenText = false,
    width = 400,
    textColor = "#000000",
    statusScope 
  } = props

  let reverseData = reverseArr(props.statusScope)

  let progressData = reverseData.map(
    (item: { id: string; stage: string; percent: number }) => (
      <div
        key={item.id}
        style={{
          width: `${item.percent}%`,
          backgroundColor: randomHexColor(+`${item.id}`),
          zIndex: `999-${item.id}`,
        }}
        className="divs"
      />
    )
  )
  
  let element = props.statusScope.find((item:any) => {
    return item.percent >= percent
  })
  
  let progressTip = element.stage

  return +percent === 100 && autoHidden ? null : (
    <div>
      <div className="progressWrap">
        <div
          className="progressBar"
          style={{ width: typeof width === 'number' ? width + 'px' : width }}>
          {progressData}
          <div
            className="themeColorBar"
            style={{ width: `${100 - percent}%`, backgroundColor: '#F1F2F3' }}
          />
        </div>
        {!hiddenText && (
          <span className="progressText" style={{ color: textColor }}>
            {percent + '%'}
          </span>
        )}
      </div>
      <div style={{ width: `${percent}%`, minWidth: `60px` }}>
        <div className="progressTip">{progressTip}</div>
      </div>
    </div>
  )
}

Progress.propTypes = {
  themeColor: PropTypes.string,
  percent: PropTypes.number,
  autoHidden: PropTypes.bool,
  textAlign: PropTypes.string,
  hiddenText: PropTypes.bool,
  width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  statusScope: PropTypes.array,
}

export default Progress
